import { IS_DEBUG } from '@/env';
import { tcmHost } from './config';
const baseHost = tcmHost;

const errorHandler = (info, showToast = false) => {
  if (showToast) {
    uni.showToast({
      title: info,
      duration: 2000,
      icon: 'none'
    })
  }
}

/**
 * 接口请求
 * @param {string} api - 接口api
 * @param {{}} options - 接口请求配置
 * @param {boolean} options.showToast - 有异常时，是否提醒用户
 * @param {boolean} options.showLoading - 是否显示loading
 */
const request = (api, options = {}) => {
  const { showToast = false, showLoading = false, params, method = "post", host, ...requestOptions } = options;
  const storeId = uni.getStorageSync("storeId");
  const token = uni.getStorageSync("token");
  const userInfo = uni.getStorageSync("userInfo") || {};
  const { unionid, openid } = userInfo;

  const Host = host ? host : baseHost;

  if (showLoading) {
    uni.showLoading({
      title: "加载中"
    })
  }

  const header = {
    'content-type': 'application/json',
    token,
    storeId,
    unionId: unionid,
    openId: openid,
  }

  // console.log("---------------->params:", params)
  // console.log("---------------->token", token)
  // console.log("---------------->userInfo", userInfo)
  // console.log("===============>header", header)
  // console.log("===============>url", `${Host}${api}`)

  return new Promise((resolve, reject) => {
    uni.request({
      url: `${Host}${api}`,
      method: method,
      data: params,
      header,
      success: (res) => {
        if (showLoading) {
          uni.hideLoading();
        }
        const { data, code, info, message } = res.data;
        // console.log("============>接口返回数据", data, code)

        if (code == 401) {
          uni.removeStorageSync('token')
        }

        if (code != 0) {
          errorHandler(info || message, showToast)
          return reject(info);
        }
        resolve(data);
      },
      fail: (error) => {
        if (showLoading) {
          uni.hideLoading();
        }
        errorHandler(error, showToast)
        reject(error)
      },
      ...requestOptions,
    });
  })
}

export default request;
